<template>
  <div class="container">
    <div class="button-container">
      <div class="return-button">
        <el-button type="text" icon="el-icon-arrow-left" @click="goBack">返回</el-button>
      </div>
      <!-- 搜索框 -->
      <div class="search-box">
        <el-input placeholder="请输入姓名或电话进行搜索" v-model="searchQuery" @input="handleSearch">
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>
    <div class="table-container">
      <el-table class="custom-table" :data="pagedMemberList" style="width: 100%" row-key="phone">
        <el-table-column prop="name" width="180" label="姓名"></el-table-column>
        <el-table-column prop="gender" width="120" label="性别"></el-table-column>
        <el-table-column prop="birthday" width="180" label="生日"></el-table-column>
        <el-table-column prop="phone" label="电话" width="150"></el-table-column>
        <el-table-column prop="registerDate" width="180" label="注册日期"></el-table-column>
        <el-table-column prop="cardType" label="卡种" width="120"></el-table-column>
        <el-table-column prop="expiryDate" width="180" label="到期时间"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-dropdown @command="(command) => handleCommand(command, scope.row)" :hide-on-click="false">
              <span class="el-dropdown-link">
                续期<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{cardType: '次卡'}">次卡</el-dropdown-item>
                <el-dropdown-item :command="{cardType: '月卡'}">月卡</el-dropdown-item>
                <el-dropdown-item :command="{cardType: '季卡'}">季卡</el-dropdown-item>
                <el-dropdown-item :command="{cardType: '年卡'}">年卡</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button type="text" @click="() => handleDelete(scope.row)" icon="el-icon-delete" class="delete-button">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 续期对话框 -->
    <el-dialog title="续期" :visible.sync="dialogVisible" width="30%">
      <el-form :model="renewForm">
        <el-form-item label="新注册日期">
          <el-date-picker v-model="renewForm.registerDate" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRenew">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentPage: 1,
      pagesize: 10,
      total: 0,
      memberList: [],
      searchQuery: '',
      dialogVisible: false,
      renewForm: {
        name: '',
        gender: '',
        birthday: '',
        phone: '',
        registerDate: '',
        cardType: '',
        expiryDate: ''
      }
    };
  },
  computed: {
    pagedMemberList() {
      const start = (this.currentPage - 1) * this.pagesize;
      const end = start + this.pagesize;
      return this.memberList.slice(start, end);
    },
  },
  methods: {
    handleSizeChange(val) {
      this.pagesize = val;
      this.currentPage = 1; // 重置当前页为第一页
      this.fetchMembers();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchMembers();
    },
    goBack() {
      this.$router.push('/member');
    },
    handleCommand(command, row) {
      this.renewForm = { ...row, cardType: command.cardType }; // 复制当前行数据到续期表单
      this.dialogVisible = true;
    },
    confirmRenew() {
      const newExpiryDate = this.calculateExpireDate(this.renewForm.registerDate, this.renewForm.cardType);
      if (!newExpiryDate) {
        this.$message.error('无法计算新的到期日期');
        return;
      }
      this.renewForm.expiryDate = newExpiryDate; // 更新续期表单中的到期日期

      axios.put(`http://localhost:8080/api/members/${this.renewForm.phone}`, this.renewForm)
        .then(response => {
          this.$message({
            type: 'success',
            message: '会员续期成功!',
          });
          this.dialogVisible = false;
          this.fetchMembers();
        })
        .catch(error => {
          console.error(error);
          this.$message.error('更新失败');
        });
    },
    calculateExpireDate(registerDate, cardType) {
      if (!registerDate) {
        this.$message.error('注册日期无效');
        return '';
      }

      const date = new Date(registerDate);
      if (isNaN(date.getTime())) {
        this.$message.error('注册日期格式错误');
        return '';
      }

      let duration;
      switch (cardType) {
        case '次卡':
          duration = 365;
          break;
        case '月卡':
          duration = 31;
          break;
        case '季卡':
          duration = 93;
          break;
        case '年卡':
          duration = 365;
          break;
        default:
          duration = 365;
      }
      date.setDate(date.getDate() + duration);
      return date.toISOString().split('T')[0];
    },
    handleDelete(row) {
      if (!row || !row.name) {
        this.$message.error('会员信息不完整');
        return;
      }

      axios.delete(`/api/members/${row.name}`)
        .then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!',
          });
          this.fetchMembers();
        })
        .catch(error => {
          console.error(error);
          this.$message.error('删除失败');
        });
    },
    fetchMembers() {
      axios.get(`/api/members?page=${this.currentPage - 1}&size=${this.pagesize}&search=${encodeURIComponent(this.searchQuery)}`)
        .then(response => {
          this.memberList = response.data.content;
          this.total = response.data.totalElements;
        })
        .catch(error => {
          console.error('获取会员列表失败:', error);
        });
    },
    handleSearch() {
      this.currentPage = 1; // 重置当前页为第一页
      this.fetchMembers();
    },
  },
  created() {
    this.fetchMembers();
  },
};
</script>

<style scoped>
.container {
  background-color: aquamarine;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.button-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  position: absolute;
  top: 20px;
  right: 20px;
}

.return-button {
  position: absolute;
  top: 10px;
  right: 20px;
}

.search-box {
  position: absolute;
  top: 10px;
  left: 100px; /* 根据返回按钮的位置调整 */
}

.table-container {
  width: 100%;
  max-width: 1400px; /* 增加表格的最大宽度 */
  margin: auto;
}

.custom-table .el-table__body-wrapper {
  background-color: #e03535;
}

.custom-table .el-table__row:hover {
  background-color: #3cc46c;
}

.delete-button {
  color: #f56c6c;
  margin-left: 10px;
}
</style>